// Decompress.cpp -- Decompress Class Implementation for decompressing DOS
//     Lemmings binary files (*.DAT)
// Copyright (C) 2008  Morgan Conbere
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
// USA.
//
// $Id: Decompress.cpp 18 2008-12-26 20:33:33Z mconbere $
//

#include <stdint.h>

#include <iostream>

#include "../util/Util.h"
#include "Decompress.h"

namespace decompress
{

Decompress::Decompress(std::istream &in)
{
    const int cHeaderSize = 10;
    uint8_t buffer[cHeaderSize];
    
    while( !in.eof() )
    {
        in.read((char *)buffer, 10);
        uint8_t bitsLeft = ((uint8_t*)buffer)[0];
        uint8_t checkSum = ((uint8_t*)buffer)[1];
        uint16_t decompressedSize = util::Swap(((uint16_t*)buffer)[2]);
        uint16_t compressedSize = util::Swap(((uint16_t*)buffer)[4]) - 10;
        
        Section section(bitsLeft, checkSum, decompressedSize, compressedSize);
        
        uint8_t* compressedBuffer = new uint8_t[section.header().compressedSize()];
        in.read((char *)compressedBuffer, section.header().compressedSize());
        bool result = section.decompress(compressedBuffer);
        if(result == false)
        {
            std::cerr << "Error in decompression: CheckSum failed" << std::endl;
        }
        else
        {
            mSections.push_back(section);
        }
        delete[] compressedBuffer;
    }
}

void Decompress::print(std::ostream &out)
{
    out << "Section count: " << mSections.size() << std::endl;
    for(unsigned int i = 0; i < mSections.size(); ++i)
    {
        mSections[i].print(out);
    }
}

} // namespace decompress